<template>
  <div>
    <Breadcrumb></Breadcrumb>
    <div id="fullscreen" class="_layout_main_">

        <!--分页搜索-->
        <a-form
            ref="defSearch"
            :model="search.def"
            :rules="search.defRules"
            layout="inline"
            class="_search_from_">

          <!--        <a-form-item label="昵称" name="name" class="_270w">-->
          <!--          <a-input v-model:value="search.def.name" placeholder="请输入用户昵称" :allowClear="true"></a-input>-->
          <!--        </a-form-item>-->

          <a-form-item label="账号" name="account" class="_270w">
            <a-input v-model:value="search.def.account" placeholder="请输入用户账号" :allowClear="true"></a-input>
          </a-form-item>

          <a-form-item label="角色" name="role" class="_270w">
            <a-select v-model:value="search.def.role" mode="multiple" placeholder="请选择角色" :allowClear="true">
              <a-select-option v-for="(item,index) in option.role" :value=item.id>
                {{
                  item.name
                }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <div style="flex: 1 1 0;"/>

          <a-form-item style="margin-right: 0">
            <a-button type="primary" @click="queryPage_">查询</a-button>
            <a-button style="margin-left: 10px" @click="()=>{ resetForm_('defSearch'); }">重置</a-button>
          </a-form-item>

        </a-form>

        <!--表格选项-->
        <div class="_tools_">
          <div style="color: rgba(0,0,0,.85);font-size: 16px;">查询表格</div>

          <div style="flex: 1 1 0"></div>

          <a-button type="primary" size="small" ghost @click="openDefAdd_()">新建</a-button>

          <a-divider type="vertical"/>

          <a-tooltip placement="top">
            <template #title>
              <span>批量删除</span>
            </template>
            <delete-outlined :style="{fontSize: '16px'}" @click="delDefs_"/>
          </a-tooltip>

          <a-tooltip placement="top">
            <template #title>
              <span>表格大小</span>
            </template>
            <a-dropdown :trigger="['click']">
              <setting-outlined :style="{fontSize: '16px'}" class="_magl14"/>
              <template #overlay>
                <a-menu v-model:selectedKeys="table.def.size" @click="(item)=>{table.def.size=item.key}">
                  <a-menu-item v-for="(item,index) in option.tableSize" :key="item.key">
                    <div style="padding: 0 5px">
                      {{ item.text }}
                    </div>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>

          </a-tooltip>

          <a-tooltip placement="top">
            <template #title>
              <span>全 屏</span>
            </template>
            <fullscreen-outlined :style="{fontSize: '16px'}" class="_magl14" @click="fullScreen"/>
          </a-tooltip>

        </div>

        <!--表格数据-->
        <a-table
            ref="defTable"
            rowKey="id"
            :pagination="false"
            :size="table.def.size"
            :columns="table.def.column"
            :data-source="table.def.data"
            :rowSelection="defRowSelection_()"
            @resizeColumn="(w, col) => {col.width = w;}">

          <!--表格内容-->
          <template #bodyCell="{ text, record, index, column  }">
            <!--角色-->
            <template v-if="column.dataIndex === 'role'">
              <a-tag v-for=" (item,index) in (record.role_ids.split(','))" color="cyan">{{ getRoleName_(item) }}</a-tag>
            </template>

            <!--操作-->
            <template v-if="column.dataIndex === 'action'">

              <!--编辑-->
              <a @click="openDefEdit_(record)">编辑</a>
              <a-divider type="vertical"/>

              <!--详情-->
              <a @click="openDefInfo_(record)">详情</a>
              <a-divider type="vertical"/>

              <!--删除-->
              <a-popconfirm placement="bottom" ok-text="确定" cancel-text="取消" @confirm="delDef_(record)">
                <template #title>
                  <p>是否执行删除操作</p>
                </template>
                <a>删除</a>
              </a-popconfirm>
              <a-divider type="vertical"/>

              <!--重置密码-->
              <a @click="resetPassword_(record)">重置密码</a>

            </template>

          </template>

        </a-table>

        <!--新增账号功能-->
        <a-modal
            title="新增账号"
            width="70%"
            v-model:visible="show.defAdd"
            :destroyOnClose="true"
            :maskClosable="false">

          <!--新增表单-->
          <a-form
              ref="defForm"
              :model="form.def.data"
              :rules="form.def.rules"
              :label-col="form.def.lc"
              :wrapper-col="form.def.wc">

            <a-form-item label="账号" name="account">
              <a-input v-model:value="form.def.data.account" placeholder="请输入账号" :allowClear="true"/>
            </a-form-item>

            <a-form-item label="密码" name="password">
              <a-input-password v-model:value="form.def.data.password" placeholder="请输入密码" :allowClear="true"/>
            </a-form-item>

            <a-form-item label="角色" name="role">
              <a-select mode="multiple" v-model:value="form.def.data.role" placeholder="请选择角色">
                <a-select-option v-for="(item,index) in option.role" :value=item.id>
                  {{
                    item.name
                  }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="手机号" name="phone">
              <a-input v-model:value="form.def.data.phone" placeholder="请输入手机号" :allowClear="true"/>
            </a-form-item>

            <a-form-item label="邮箱" name="email">
              <a-input v-model:value="form.def.data.email" placeholder="请输入邮箱" :allowClear="true"/>
            </a-form-item>
          </a-form>

          <!--底部按钮-->
          <template #footer>
            <a-button @click="show.addRes = false">取消</a-button>
            <a-button class="_magl10" @click="()=>{resetForm_('defForm')}">重置</a-button>
            <a-button class="_magl10" type="primary" @click="addDef_()">保存</a-button>
          </template>

        </a-modal>

    </div>
  </div>
</template>

<script>
import {createVNode, defineComponent} from 'vue';
import {Modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";
import screenfull from "screenfull";
import Breadcrumb from "@/common/layout/Breadcrumb.vue";

export default defineComponent({
  name: 'SysUser',

  components: {Breadcrumb,},

  async mounted() {
    await this.queryRole_()

    this.queryPage_()

    //全局监听-刷新
    this.$event.$on('refresh', (data) => {
      if ('/system/user' == data['path']) {
      }
    })

  },

  data() {
    return {
      //开关
      show: {
        //
        defAdd: false,
        defEdit: false,
        defInfo: false,
      },

      //搜索
      search: {

        //默认搜索
        def: {
          name: "",
          account: "",
          role: [],
        },

        //默认搜索规则
        defRules: {},

      },

      //分页
      page: {

        //默认分页
        def: {
          current: 1,
          size: 10,
          total: 10,
          options: ['10', '30', '50', '100', '200', '500'],
          type: 'small',
          sizeChange: (current, pageSize) => {
            this.page.current = current;
            this.page.size = pageSize;
            this.queryPage_()
          },
          currentChange: (current) => {
            this.page.current = current
            this.queryPage_()
          }
        }

      },

      //表单
      form: {

        //默认表单
        def: {
          data: {},
          rules: {
            role: [
              {
                required: true,
                message: '必选项',
                trigger: 'blur',
              },
            ],
            account: [
              {
                required: true,
                message: '必填项',
                trigger: 'blur',
              },
              {
                min: 5,
                message: '长度至少5位字符',
                trigger: 'blur',
              },
              {
                max: 20,
                message: '长度最多20位字符',
                trigger: 'blur',
              },
            ],
            password: [
              {
                required: true,
                max: 20,
                message: '长度最多20位字符（可以为空）',
                trigger: 'blur',
              },
              {
                validator: (_rule, value) => {
                  if (!value || value.length == 0) {
                    return Promise.resolve();
                  }
                  if (value.length < 5) {
                    return Promise.reject('长度至少5位字符（可以为空）');
                  }
                  return Promise.resolve();
                }, trigger: 'blur'
              }
            ],
          },
          lc: {span: 3},
          wc: {span: 19},
          searchRules: {},
          //(初始化/重置)Data
          resetData: {
            role: ['10'],
            account: null,
            password: null,
            email: null,
            phone: null,
          },
        },

        //功能表单
        api: {
          data: {},
          rules: {
            sort: [
              {
                type: 'any',
                required: true,
                message: '必填项',
                trigger: 'blur',
              },
            ],
            name: [
              {
                type: 'any',
                required: true,
                message: '必填项',
                trigger: 'blur',
              },
            ],
            path: [
              {
                type: 'any',
                required: true,
                message: '必填项',
                trigger: 'blur',
              },
            ],
            type: [
              {
                type: 'any',
                required: true,
                message: '必填项',
                trigger: 'blur',
              },
            ],
            api_info: [],
          },
          lc: {span: 4},
          wc: {span: 16},
          searchRules: {},
          //(初始化/重置)Data
          resetData: {
            name: null,
            type: "1",
            des: null,
            sort: 100,
            api_info: [],
          },
        },

      },

      //表格
      table: {

        //默认表格
        def: {
          size: 'middle',
          data: [],
          column: [
            {title: 'ID', dataIndex: 'id', resizable: true, width: 220},
            {title: '账号', dataIndex: 'account', resizable: true, width: 220},
            // {title: '昵称', dataIndex: 'name', resizable: true, width: 220},
            {title: '角色', dataIndex: 'role', resizable: true, width: 200},
            {title: '排序', dataIndex: 'sort', resizable: true, align: 'center', width: 100},
            {title: '操作', dataIndex: 'action', align: 'center', width: 300},
          ],
          selectKey: [],
          selectRow: [],
        },

      },

      //自动完成
      auto: {
        name: [],
      },

      //option选项
      option: {
        role: [],
        menuRes: [
          {key: '0', text: '按钮'},
          {key: '1', text: '非按钮'},
        ],
        tableSize: [
          {key: 'default', text: '大号'},
          {key: 'middle', text: '中号'},
          {key: 'small', text: '小号'},
        ],
        menuIsSHow: [
          {key: '0', text: '展示',},
          {key: '1', text: '隐藏'},
        ],
      },
    };
  },

  methods: {

    //分页查询
    queryPage_() {
      let param = {
        ...this.search.def
      }
      this.$http.post('/system/user/page', param).then((res) => {
        if (res.status) {
          this.table.def.data = this.$kit.getTree(res.data)
        } else {
          this.$message.warning(res.message)
        }
      })
    },

    //查询角色
    queryRole_() {
      this.$http.post('/system/user/roleList', {}).then((res) => {
        if (res.status) {
          this.option.role = res.data
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //解析角色名
    getRoleName_(id) {
      let name = '';
      this.option.role.filter(e => {
        if (e.id == id) {
          name = e.name
        }
      })
      return name;
    },

    //初始化表单
    resetDef_() {
      this.form.def.data = JSON.parse(JSON.stringify(this.form.def.resetData))
    },

    //重置表单
    resetForm_(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields()
      }
    },

    //打开新增
    openDefAdd_() {
      this.resetDef_()
      this.show.defAdd = true
    },

    //打开编辑
    openDefEdit_(obj) {
      let row = JSON.parse(JSON.stringify(obj))
      this.show.defEdit = true
      this.form.def.data = row;
    },

    //打开编辑
    openDefInfo_(obj) {
      let row = JSON.parse(JSON.stringify(obj))
      this.show.defInfo = true
      this.form.def.data = row;
    },

    //执行新增
    addDef_() {
      this.$refs.defForm
          .validate()
          .then(() => {
            this.$http.post("/system/user/add", this.form.def.data).then((res) => {
              if (res.status) {
                this.$message.success(res.message)
                this.queryPage_()
                this.show.defAdd = false
              } else {
                this.$message.warning(res.message)
              }
            })
          })
          .catch(error => {
            this.$message.warning("存在错误，请检查表单填写情况。", 2)
          });
    },
    //重置密码
    resetPassword_(obj) {
      let row = JSON.parse(JSON.stringify(obj))
      this.$http.post("/system/user/resetPassword", {ids: [row.id]}).then((res) => {
        if (res.status) {
          this.$message.success(res.message)
          this.queryPage_()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //执行删除
    delDef_(obj) {
      let row = JSON.parse(JSON.stringify(obj))
      this.$http.post("/system/user/del", {ids: [row.id]}).then((res) => {
        if (res.status) {
          this.$message.success(res.message)
          this.queryPage_()
        } else {
          this.$message.warning(res.message)
        }
      })
    },

    //批量删除
    delDefs_() {
      let keys = this.table.def.selectKey;
      if (keys.length === 0) {
        this.$message.warn("请至少勾选一项", 1)
        return
      }

      Modal.confirm({
        title: '是否确定删除?',
        icon: createVNode(ExclamationCircleOutlined),
        content: `已勾选${keys.length}条数据`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.$http.post("/system/user/del", {ids: keys}).then((res) => {
            if (res.status) {
              this.$message.success(res.message)
              this.queryPage_()
            } else {
              this.$message.warning(res.message)
            }
          })
        },
        onCancel: () => {
          this.$message.warning("操作已取消", 1)
        },
      });

    },

    //全屏
    fullScreen() {
      let element = document.getElementById("fullscreen")
      if (screenfull.isEnabled) {
        screenfull.request(element)
      }
      screenfull.toggle()
    },

    //表格多选
    defRowSelection_() {
      return {
        type: "checkbox",
        checkStrictly: false,
        preserveSelectedRowKeys: false,//翻页后保留选中状态
        selectedRowKeys: this.table.def.selectKey,
        onChange: (selectedRowKeys, selectedRows) => {
          ////console.log("onChange")
          this.table.def.selectKey = selectedRowKeys
          this.table.def.selectRow = selectedRows
        },
        onSelect: (record, selected, selectedRows) => {
          ////console.log("onSelect")
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
          ////console.log("onSelectAll")
        },
      }
    },
  }

});

</script>

<style>

</style>
